<template>
  <div class="map-area-wrapper">
    <div :id="props.id" class="map-area"></div>
    <div class="map-area-search">
      <a-input-search
        class="search-input"
        :style="{ width: '320px', marginBottom: '10px' }"
        placeholder="请输入地址搜索"
        search-button
        @search="handleSearch"
      />
      <div :id="searchId" class="search-pannel"></div>
    </div>
    <div class="bottom-tools">
      <a-progress :percent="percent" :style="{ width: '50%' }" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import {
    ref,
    onUnmounted,
    onMounted,
    withDefaults,
    defineProps,
    nextTick,
    defineExpose,
  } from 'vue';
  import { random } from 'lodash';
  import { initMapFile } from '@/utils/initMap';
  import { number } from 'echarts';

  interface Props {
    id?: string;
    tools: string[];
  }
  const props = withDefaults(defineProps<Props>(), {
    id: 'map-container',
    tools: () => {
      return [];
    },
  });

  const percent = ref(0);
  let map: any = null;
  let initLoading = false;
  let lineArrLocal: number[][] = [];
  let placeSearch: any = null;
  let curMaker: any = null;
  let passedPolyline: any = null;
  let polyline: any = null;

  const searchId = `search-${Date.now()}-${random(1000, 9999)}`;

  const initMap = () => {
    map = new window.AMap.Map(props.id, {
      resizeEnable: true,
      zoom: 17,
    });

    placeSearch = new window.AMap.PlaceSearch({
      map,
      panel: searchId,
      autoFitView: true,
    }); //
  };

  const initMapLoader = () => {
    return new Promise<void>((resolve, reject) => {
      if (initLoading) {
        resolve();
        return;
      }
      if (!window.AMap) {
        initLoading = true;
        initMapFile()
          .then((res) => {
            initLoading = false;
            window.AMap = res;
            initMap();
            resolve();
          })
          .catch((e) => {
            console.log(e);
            reject(e);
          });
      } else {
        if (!map) {
          initMap();
        }
        resolve();
      }
    });
  };

  const setLine = () => {
    curMaker = new window.AMap.Marker({
      map,
      position: lineArrLocal[0],
      icon: 'https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png',
      offset: new window.AMap.Pixel(-13, -26),
    });

    // 绘制轨迹
    polyline = new window.AMap.Polyline({
      map,
      path: lineArrLocal,
      showDir: true,
      strokeColor: '#28F', // 线颜色
      strokeWeight: 6, // 线宽
    });

    passedPolyline = new window.AMap.Polyline({
      map,
      strokeColor: '#AF5', // 线颜色
      strokeWeight: 6, // 线宽
    });

    curMaker.on('moving', (e) => {
      const { progress, index } = e;
      const step = 1 / (lineArrLocal.length - 1);
      const has = step * index + step * progress;
      percent.value = Number(has.toFixed(2));
      passedPolyline.setPath(e.passedPath);
      map.setCenter(e.target.getPosition(), true);
    });

    map.setFitView();

    curMaker.moveAlong(lineArrLocal, {
      // 每一段的时长
      duration: 500, // 可根据实际采集时间间隔设置
      // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
      autoRotation: true,
    });
    stop();
  };

  const handleSearch = (val: string) => {
    if (placeSearch) {
      placeSearch.search(val);
    }
  };

  const setLineData = (list: number[][]) => {
    if (map) {
      percent.value = 0;
      if (curMaker) {
        curMaker.stopMove();
        map.remove(curMaker);
      }

      if (polyline) {
        map.remove(polyline);
      }

      if (passedPolyline) {
        map.remove(passedPolyline);
      }

      map.clearMap();
      if (list?.length) {
        lineArrLocal = list;
        setLine();
      }
    }
  };

  const stop = () => {
    curMaker.pauseMove();
  };
  const play = () => {
    curMaker.resumeMove();
  };

  defineExpose({
    setLineData,
    stop,
    play,
  });

  onMounted(() => {
    nextTick(() => {
      initMapLoader();
    });
  });

  onUnmounted(() => {
    map?.destroy();
  });
</script>

<style lang="less">
  .map-area-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
    padding-bottom: 40px;
    .map-area-search {
      position: absolute;
      right: 12px;
      top: 12px;
      z-index: 10;
    }
    .search-pannel {
      position: absolute;
      right: 12px;
      top: 34px;
      height: 300px;
      width: 300px;
      z-index: 10;
      overflow: auto;
    }
    .arco-input-wrapper {
      background: #fff;
    }
    .bottom-tools {
      position: absolute;
      width: 100%;
      height: 40px;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .map-area {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
</style>
